//package com.example.last.utils;
//
//import cn.hutool.core.util.StrUtil;
//import com.auth0.jwt.JWT;
//import com.auth0.jwt.JWTVerifier;
//import com.auth0.jwt.algorithms.Algorithm;
//import com.auth0.jwt.exceptions.JWTVerificationException;
//import com.example.last.common.enums.ErrorCode;
//import com.example.last.entity.Admin;
//import com.example.last.exception.CustomException;
//import com.example.last.service.AdminService;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.stereotype.Component;
//import org.springframework.web.servlet.HandlerInterceptor;
//
//import javax.annotation.Resource;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
//@Component
//public class JwtInterceptor implements HandlerInterceptor {
//    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);
//
//    @Resource
//    private AdminService adminService;
//
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        // 1. 从http请求的header获取token
//        String token = request.getHeader("token");
//        if (StrUtil.isBlank(token)) {
//            token = request.getParameter("token");//从参数获取一遍：/api/admin?Token=xxx&？？？
//        }
//
//        // 2. 开始执行认证
//        if (StrUtil.isBlank(token)) {
//            throw new CustomException(ErrorCode.TOKEN_INVALID_ERROR);
//        }
//
//        // 获取token中的userId
//        String userId;
//        Admin admin;
//        try {
//            userId = JWT.decode(token).getAudience().get(0);
//            // 根据token中的userId查询数据库
//            admin = adminService.findById(Integer.parseInt(userId));
//        } catch (Exception e) {
//            throw new CustomException(ErrorCode.TOKEN_CHECK_ERROR);
//        }
//
//        if (admin == null) {
//            throw new CustomException(ErrorCode.USER_NOT_EXIST_ERROR);
//        }
//        try {
//            // 用密码加盐验证 token
//            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(admin.getPassword())).build();
//            jwtVerifier.verify(token); // 验证token
//        } catch (JWTVerificationException e) {
//            throw new CustomException(ErrorCode.TOKEN_CHECK_ERROR);
//        }
//
//        log.info("token验证成功，允许放行");
//        return true;
//
//    }
//}
